{% extends "teacher/base.html" %}

{% block title %}班级信息管理 - 期末成绩登记统计分析系统{% endblock %}

{% block styles %}
<style>
  .main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    margin-left: 250px;
    /* 为侧边栏留出空间 */
    margin-top: 60px;
    /* 为顶部导航栏留出空间 */
    min-height: calc(100vh - 60px);
    /* 减去导航栏高度 */
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    background: white;
    padding: 15px 20px;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 60px;
    /* 导航栏高度 */
    z-index: 100;
  }

  .search-box {
    display: flex;
    gap: 12px;
    flex: 1;
    max-width: 400px;
  }

  .search-box input {
    flex: 1;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  .search-box input:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .btn {
    padding: 10px 20px;
    border: none;
    border-radius: var(--border-radius);
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.3s ease;
  }

  .btn i {
    font-size: 16px;
  }

  .btn-primary {
    background: var(--primary-blue);
    color: white;
  }

  .btn-primary:hover {
    background: #0873c4;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .btn-danger {
    background: #ff6b6b;
    color: white;
  }

  .btn-danger:hover {
    background: #ff5252;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
  }

  .btn-success {
    background: #00b894;
    color: white;
  }

  .btn-success:hover {
    background: #00a884;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 184, 148, 0.2);
  }

  .table-container {
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .table-container:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
  }

  .table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
  }

  .table th,
  .table td {
    padding: 15px 20px;
    text-align: left;
    border-bottom: 1px solid #eee;
  }

  .table th {
    background: #f8f9fa;
    font-weight: 600;
    color: var(--text-primary);
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .table td {
    color: var(--text-secondary);
    font-size: 14px;
  }

  .table tr:last-child td {
    border-bottom: none;
  }

  .table tr:hover td {
    background: #f8f9fa;
  }

  .table td .btn {
    padding: 6px 12px;
    font-size: 13px;
  }

  .modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    backdrop-filter: blur(4px);
  }

  .modal-content {
    position: relative;
    background: white;
    margin: 5% auto;
    width: 450px;
    border-radius: var(--border-radius);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    animation: modalSlideIn 0.3s ease;
  }

  @keyframes modalSlideIn {
    from {
      transform: translateY(-20px);
      opacity: 0;
    }

    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  .modal-header {
    padding: 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .modal-title {
    font-size: 20px;
    color: var(--text-primary);
    margin: 0;
    font-weight: 600;
  }

  .close {
    font-size: 24px;
    color: #666;
    cursor: pointer;
    transition: all 0.2s ease;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }

  .close:hover {
    background: #f8f9fa;
    color: var(--text-primary);
  }

  .form-group {
    margin-bottom: 20px;
    padding: 0 20px;
  }

  .form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--text-secondary);
    font-weight: 500;
    font-size: 14px;
  }

  .form-group input,
  .form-group select {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #e0e0e0;
    border-radius: var(--border-radius);
    font-size: 14px;
    transition: all 0.3s ease;
  }

  .form-group input:focus,
  .form-group select:focus {
    border-color: var(--primary-blue);
    box-shadow: 0 0 0 2px rgba(9, 132, 227, 0.1);
    outline: none;
  }

  .modal-footer {
    padding: 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 25px;
    padding: 15px;
    background: white;
    border-radius: var(--border-radius);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .pagination .btn {
    padding: 8px 16px;
    min-width: 100px;
    background: white;
    color: var(--primary-blue);
    border: 1px solid var(--primary-blue);
    transition: all 0.3s ease;
  }

  .pagination .btn:hover:not(:disabled) {
    background: var(--primary-blue);
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(9, 132, 227, 0.2);
  }

  .pagination .btn:disabled {
    background: #f8f9fa;
    color: #6c757d;
    border-color: #dee2e6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .current-page {
    color: var(--text-primary);
    font-weight: 500;
    font-size: 14px;
    padding: 0 15px;
  }

  /* 响应式布局调整 */
  @media (max-width: 768px) {
    .main-content {
      margin-left: 0;
      padding: 15px;
    }

    .action-bar {
      position: relative;
      top: 0;
    }

    .search-box {
      max-width: 100%;
    }

    .table-container {
      overflow-x: auto;
    }

    .modal-content {
      width: 90%;
      margin: 10% auto;
    }

    .pagination {
      flex-direction: column;
      gap: 10px;
      padding: 10px;
    }

    .pagination .btn {
      width: 100%;
    }

    .current-page {
      order: -1;
      margin-bottom: 5px;
    }
  }
</style>
{% endblock %}

{% block content %}
<div class="action-bar">
  <div class="search-box">
    <input type="text" id="searchInput" placeholder="搜索班级...">
    <button class="btn btn-primary" onclick="searchClasses()">搜索</button>
  </div>
  <button class="btn btn-primary" onclick="showAddModal()">添加班级</button>
</div>

<div class="table-container">
  <table class="table">
    <thead>
      <tr>
        <th>班级编号</th>
        <th>班级名称</th>
        <th>所属学院</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="classTableBody">
      {# 遍历分页对象时要加 .items #}
      {% for class, college_name in classes.items %}
      <tr>
        <td>{{ class.class_id }}</td>
        <td>{{ class.class_name }}</td>
        <td>{{ college_name }}</td>
        <td>
          <button class="btn btn-primary" onclick="showEditModal('{{ class.class_id }}')">编辑</button>
          <button class="btn btn-danger" onclick="deleteClass('{{ class.class_id }}')">删除</button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <!-- 分页控件 -->
  {% if classes.total > 20 %}
  <div class="pagination">
    {% if classes.has_prev %}
    <a href="{{ url_for('teacher_class.classes', page=classes.prev_num) }}" class="btn btn-primary">上一页</a>
    {% else %}
    <button class="btn" disabled>上一页</button>
    {% endif %}

    <span class="current-page">第 {{ classes.page }} 页，共 {{ classes.pages }} 页</span>

    {% if classes.has_next %}
    <a href="{{ url_for('teacher_class.classes', page=classes.next_num) }}" class="btn btn-primary">下一页</a>
    {% else %}
    <button class="btn" disabled>下一页</button>
    {% endif %}
  </div>
  {% endif %}
</div>

<!-- 添加/编辑班级模态框 -->
<div id="classModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title" id="modalTitle">添加班级</h3>
      <span class="close" onclick="closeModal()">&times;</span>
    </div>
    <form id="classForm">
      <input type="hidden" id="classId">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <div class="form-group">
        <label for="className">班级名称</label>
        <input type="text" id="className" required>
      </div>
      <div class="form-group">
        <label for="collegeId">所属学院</label>
        <select id="collegeId" required>
          {% for college in colleges %}
          <option value="{{ college.college_id }}">{{ college.college_name }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" onclick="closeModal()">取消</button>
        <button type="submit" class="btn btn-success">保存</button>
      </div>
    </form>
  </div>
</div>

<script>
  // 显示添加模态框
  function showAddModal() {
    document.getElementById('modalTitle').textContent = '添加班级';
    document.getElementById('classForm').reset();
    document.getElementById('classId').value = '';
    document.getElementById('classModal').style.display = 'block';
  }

  // 显示编辑模态框
  function showEditModal(classId) {
    document.getElementById('modalTitle').textContent = '编辑班级';
    // 获取班级信息并填充表单
    fetch(`/teacher/api/classes/${classId}`)
      .then(response => {
        if (!response.ok) {
          throw new Error('获取班级信息失败');
        }
        return response.json();
      })
      .then(data => {
        if (data.success && data.data) {
          document.getElementById('classId').value = data.data.class_id;
          document.getElementById('className').value = data.data.class_name;
          document.getElementById('collegeId').value = data.data.college_id;
          document.getElementById('classModal').style.display = 'block';
        } else {
          throw new Error(data.message || '获取班级信息失败');
        }
      })
      .catch(error => {
        alert(error.message || '获取班级信息失败，请重试');
      });
  }

  // 关闭模态框
  function closeModal() {
    document.getElementById('classModal').style.display = 'none';
    document.getElementById('classForm').reset();
  }

  // 删除班级
  function deleteClass(classId) {
    if (!confirm('确定要删除这个班级吗？')) return;
    fetch(`/teacher/api/classes/${classId}`, {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': document.querySelector('input[name="csrf_token"]').value
      }
    })
      .then(response => response.json().catch(() => {
        throw new Error('服务器返回了非JSON格式的错误信息');
      }))
      .then(data => {
        if (data.success) {
          alert('班级删除成功');
          window.location.reload();
        } else {
          alert(data.message || '删除失败');
        }
      })
      .catch(error => {
        alert(error.message || '删除失败，请重试');
      });
  }

  // 搜索班级
  function searchClasses() {
    const searchText = document.getElementById('searchInput').value.toLowerCase();
    const rows = document.getElementById('classTableBody').getElementsByTagName('tr');

    for (let row of rows) {
      const text = row.textContent.toLowerCase();
      row.style.display = text.includes(searchText) ? '' : 'none';
    }
  }

  // 提交表单
  document.getElementById('classForm').onsubmit = function (e) {
    e.preventDefault();
    const classId = document.getElementById('classId').value;
    const className = document.getElementById('className').value;
    const collegeId = document.getElementById('collegeId').value;

    // 验证输入
    if (!className || !collegeId) {
      alert('请填写所有必填字段');
      return;
    }

    const data = {
      class_name: className,
      college_id: parseInt(collegeId)  // 确保 college_id 是数字
    };

    const url = classId ? `/teacher/api/classes/${classId}` : '/teacher/api/classes';
    const method = classId ? 'PUT' : 'POST';

    fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': document.querySelector('input[name="csrf_token"]').value
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('保存成功');
          // 关闭模态框
          closeModal();
          // 重新加载页面
          window.location.reload();
        } else {
          // 如果是班级名称已存在，弹窗提示
          if (data.message && data.message.indexOf('已存在') !== -1) {
            alert('班级名称已存在');
            return;
          }
          throw new Error(data.message || '保存失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert(error.message || '保存失败，请稍后重试');
      });
  };
</script>
{% endblock %}